package com.ej.flink.test;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Demo {
    public static void main(String[] args) throws Exception {
        /**
         * 1. 获取env环境
         * 2. 设置默认并行度
         * 3. 新建一个source
         * 4. 执行transformation 转换
         * 5. 新建一个sink
         * 6. 执行execute
         */

        Configuration conf = new Configuration();
        conf.set(RestOptions.BIND_PORT, "8081");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(conf);
        env.setParallelism(1);

        DataStreamSource<String> source = env.socketTextStream("192.168.137.10", 7777);
        source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] s = value.split(" ");
                        for (String s1 : s) {
                            Tuple2<String, Integer> tuple2 = Tuple2.of(s1, 1);
                            out.collect(tuple2);
                        }
                    }
                }).keyBy(
                        t -> t.f0
                ).sum(1)
                .print();
//        source.print();
        env.execute();
    }
}
